package com.lindroy.androidplayer.ui.main.fragment

import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import com.lindroy.androidplayer.R
import com.lindroy.androidplayer.base.BaseLazyFragment
import com.lindroy.androidplayer.databinding.FragmentOfficialAccountBinding
import com.lindroy.androidplayer.logic.network.base.http.observeResponse
import com.lindroy.androidplayer.ui.adapter.WxTabAdapter
import com.lindroy.androidplayer.utils.contactToViewPager
import com.lindroy.androidplayer.utils.toHtml
import com.lindroy.androidplayer.viewmodels.WxChapterViewModel

/**
 * @author Lin
 * @date 2022/1/10
 * @function 首页-公众号
 * @Description
 */
class WxChaptersFragment : BaseLazyFragment<FragmentOfficialAccountBinding>() {

    private lateinit var adapter: WxTabAdapter
    private val wxChapterViewModel by viewModels<WxChapterViewModel>()

    override fun FragmentOfficialAccountBinding.initView(savedInstanceState: Bundle?) {
        vm = wxChapterViewModel
        initToolbar(R.string.official_account, false)
        adapter = WxTabAdapter(this@WxChaptersFragment)
        vpWxArticle.adapter = adapter
    }

    override fun FragmentOfficialAccountBinding.initListener() {
        wxChapterViewModel.wxChapterLiveData.data.observeResponse(viewLifecycleOwner) { chapters ->
            vpWxArticle.offscreenPageLimit = chapters.size
            adapter.setData(chapters.map { it.id })
            tab.tabLayout.contactToViewPager(vpWxArticle, chapters.map { it.name.toHtml() })
        }
    }

    override fun lazyLoad() {
        wxChapterViewModel.wxChapterLiveData.load()
    }

    override fun onRetryClick(view: View) {
        super.onRetryClick(view)
        wxChapterViewModel.wxChapterLiveData.retry()
    }

    companion object{
        fun newInstance() = WxChaptersFragment()
    }
}